package org.ztest.guava;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

import io.netty.util.concurrent.DefaultThreadFactory;

public class ListenableFutureTest
{
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void test1()
	{
		ListeningExecutorService es = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor(new DefaultThreadFactory("GUAVA-TEST")));
		ListenableFuture<?> future = es.submit(() -> {
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
		// 在es线程池中执行listener
		future.addListener(() -> {
			System.out.println("LISTENER: " + Thread.currentThread());
		}, es);
		
		Futures.addCallback(future, new FutureCallback() {

			@Override
			public void onSuccess(Object result)
			{
				System.out.println("CALLBACK: " + Thread.currentThread());
			}

			@Override
			public void onFailure(Throwable t)
			{
			}
		});
	}
}
